const events = require('events')
const Lib = require("./lib");
const ws = require("ws");

class Index extends events {
    constructor(roomId) {
        super()
        this.roomId = roomId
        this.emitter = new events.EventEmitter()
        this.ws_info = new Lib(this.roomId)
    }

    start() {
        let {ws_url, login_data} = this.ws_info.get_ws_info()
        this.client = new ws(ws_url)
        this.client.on('open', res => {
            login_data.forEach((item, index) => {
                this.client.send(item)
            })
            setInterval(() => {
                console.error(this.ws_info.heartbeatInterval, '发送心跳包')
                this.client.send(this.ws_info.heartbeat)
            }, this.ws_info.heartbeatInterval);
        })
        this.client.on('message', data => {
            this.on_message(data)
        })
        this.client.on('close', async () => {

        })
    }

    stop() {
        this.client.close()
    }

    on_message(data) {
        let result = {}
        data = this.ws_info.decode(data)
        if (data.type == 'chatmsg' || data.type == 'uenter' || data.type == 'dgb') {
            data.ic = data.ic.split('@S').join('/')
        }

        if (data.type == 'chatmsg') {
            // console.log(data)
            result.type = 'chatMsg'
            result.nikeName = data.nn
            result.content = data.txt
            result.headImage = `https://apic.douyucdn.cn/upload/${data.ic}_big.jpg`
        }
        if (data.type == 'uenter') {
            result.type = 'join'
            result.nikeName = data.nn
            result.headImage = `https://apic.douyucdn.cn/upload/${data.ic}_big.jpg`
        }
        if (result.type) {
            this.emit('message', result)
        }
    }
}

exports = module.exports = Index
